package cn.buaa.anniversary.Utils;

import sun.awt.SunHints;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created this one by HMH on 2017/5/13.
 */
public class ImgUtil {

    public static  BufferedImage mixture(BufferedImage back, BufferedImage front, int x, int y) {
        Graphics g=back.getGraphics();
        //融合图像
        g.drawImage(front, x, y, front.getWidth(), front.getHeight(), null);
        g.dispose();
        return back;
    }

    public static BufferedImage addText(BufferedImage back, String text, Font font, int x, int y,Color color) {
        color = color == null ? Color.white : color;
        Graphics2D g = back.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g.setFont(font);
        g.setColor(color);
        g.drawString(text, x, y);
        g.dispose();
        return back;
    }

    public static  BufferedImage cutImage(BufferedImage srcImage, int x, int y,int width,int height) {
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = img.getGraphics();
        g.drawImage(srcImage, 0, 0, width, height, null);
        g.dispose();
        return img;
    }

    public static BufferedImage zoomImage(BufferedImage img,double zoom) {
        int width = img.getWidth();
        int height = img.getHeight();
        int toWidth = (int) (width * zoom);
        int toHeight = (int) (height * zoom);

        BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = result.getGraphics();
        g.drawImage(
                img.getScaledInstance(toWidth, toHeight,
                        Image.SCALE_SMOOTH), 0, 0, null);
        g.dispose();
        return result;
    }

    /**
     * 使用ImageIO存入文件
     * @param img 图片
     * @param file 存放路径
     * @return 保存的图片
     * @throws IOException 读写异常
     */
    public static File savePng(BufferedImage img,File file) throws IOException {
//        检查目录状态，创建文件夹
        Path path = Paths.get(file.getAbsolutePath());
        Files.createDirectories(path);
//        生成文件，png格式
        ImageIO.write(img, "png", file);
        return file;
    }
}
